<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body id="app">
    <label for="uploader">选择图片</label>
    <input type="file" value="上传" id="uploader" hidden />
  </body>
</html>
<script>
  let app = document.querySelector('#app');
  /*发送ajax*/
  //获取元素监听change事件
  let uploader = document.querySelector('#uploader');
  uploader.onchange = function () {
    //新建FormData 空对象
    let form = new FormData();
    //添加file对象
    form.append('file', this.files[0]);
    //新建xmlhttprequest 对象
    let xhr = new XMLHttpRequest();
    //配置xhr
    xhr.open('post', '/index.json');
    // xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    //发送
    xhr.send(form);
    //监听onload 方法
    xhr.onload = function () {
      //判断返回状态码是否为200
      if (xhr.status == 200) {
        console.log(JSON.parse(xhr.responseText));
      }
    };
    /*插入图片*/
    //创建一个img标签
    let img = document.createElement('img');
    //创建file对象url
    src = window.URL.createObjectURL(this.files[0]);
    //src属性赋值
    img.src = src;
    // 加载完成后放到body标签
    img.onload = function () {
      app.appendChild(img);
    };
  };
</script>